package ru.pomarshrutu.client.controller;

import ru.pomarshrutu.client.view.UploadPage;
import ru.pomarshrutu.client.view.UploadRecordingWidget;
import ru.pomarshrutu.client.view.UploadRecordingWidgetListener;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.user.client.Window;

public class Controller implements UploadRecordingWidgetListener {
	private static final String REMOVE_POINT_REQUEST_URL = GWT.getModuleBaseURL() + "simpleupload?action=removePoint";
	private UploadPage view;
	
	public void setView(UploadPage view) {
		this.view = view;
	}
	
	private void removePoint(LatLng coordinates) {
		RequestBuilder requestBuilder = new RequestBuilder(
				RequestBuilder.GET, 
				REMOVE_POINT_REQUEST_URL + "&coordinates=" + coordinates.toUrlValue()
		);
		try {
			requestBuilder.sendRequest(
					null, 
					new RequestCallback() {
				
						@Override
						public void onResponseReceived(Request request, Response response) {
							if(response.getStatusCode() != Response.SC_OK) {
								view.displayResponseError(response.getStatusText());
							}
						}
						
						@Override
						public void onError(Request request, Throwable exception) {
							view.displayResponseError("onError: " + exception);							
						}
					}
			);
		} catch (RequestException e) {
			view.displayResponseError("RequestException: " + e.getMessage());
		}
		
	}
	
	@Override
	public void onUpload(UploadRecordingWidget widget) {
		String fileName = widget.getFileName();
		if(fileName == null || fileName.length() == 0) {
			Window.alert("Выберите файл!");
			return;
		}
		
		widget.submit();
	}

	@Override
	public void onRemove(UploadRecordingWidget widget) {
		if(widget.getState() == UploadRecordingWidget.State.SUBMITTED_OK) {
			if(!Window.confirm("Вы уверены, что хотите удалить точку и связанную с ней запись?"))
				return;
			
			removePoint(widget.getCoordinates());
		}
				
		if(view != null)
			view.removeUploadWidget(widget);
		
		return;
	}
}
